<!DOCTYPE html>
<html>

<head>
  <script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
  <meta charset="utf-8" />
  <title>Konva 图层层级</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <div id="container"></div>

  <script>
    var width = window.innerWidth
    var height = window.innerHeight

    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height
    })
    var animLayer = new Konva.Layer()
    var staticLayer = new Konva.Layer()

    /*
     * 保持中心点定位
     * 在中间的默认值
     * 六边形
     */

    var blueHex = new Konva.RegularPolygon({
      x: 50,
      y: stage.height() / 2,
      sides: 6,
      radius: 40,
      fill: '#00D2FF',
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    })

    var yellowHex = new Konva.RegularPolygon({
      x: stage.width() / 2,
      y: stage.height() / 2,
      sides: 6,
      radius: 30,
      fill: 'yellow',
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    })

    /*
     * move center point to right side
     * of hexagon
     */
    var redHex = new Konva.RegularPolygon({
      x: 250,
      y: stage.height() / 2,
      sides: 6,
      radius: 30,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4,
      offset: {
        x: 30,
        y: 0
      },
      draggable: true
    })

    var text = new Konva.Text({
      x: 10,
      y: 10,
      text: '图层示例',
      fontSize: '30',
      fontFamily: 'Calibri',
      fill: 'black',
      padding: 10,
      draggable: true,
    })

    staticLayer.add(text)

    animLayer.add(blueHex, yellowHex, redHex)
    stage.add(animLayer, staticLayer)

    // 定义动画周期为2000毫秒
    var period = 2000
    var anim = new Konva.Animation(function (frame) {
      /* 
          计算当前帧的缩放比例
            frame.time 表示动画已执行的时间（毫秒）
            Math.sin(...) 产生一个周期性的正弦值，范围在 -1 到 1 之间
              这里通过 (frame.time * 2 * Math.PI) / period 将时间转换为正弦函数的输入
              使其完整周期匹配动画周期
              +0.001 确保缩放比例永不为零，避免在缩放时产生无效或异常的行为
      */
      var scale = Math.sin((frame.time * 2 * Math.PI) / period) + 0.001
      blueHex.scale({ x: scale, y: scale })
      yellowHex.scaleY(scale)
      redHex.scaleX(scale)

    }, animLayer)

    anim.start();
  </script>
</body>

</html>